from flask import Flask, session, render_template, redirect, Blueprint, request

# 导入数据表模型
from model.User import User
from model.History import History   # 因为外键是user表的主键，故需要传入

# 导入errorResponse函数
from utils.errorResponse import *

# 导入app、db文件
from app import app
from db import db

ub = Blueprint('user', __name__, url_prefix='/user', template_folder='templates')

# 登录页面
@ub.route('/login', methods =['GET', 'POST'])
def login():
    if request.method == 'POST':
        user = User.query.filter_by(user_name = request.form['username'], user_password = request.form['password']).first()
        # print(user.user_name)
        if user:
            session['username'] = user.user_name
            return redirect('/page/home')
        else:
            return errorResponse('用户名或密码错误！')
    else:
        return render_template('login.html')

# 注册页面
@ub.route('/register', methods =['GET', 'POST'])
def register():
    if request.method == 'POST':
        user = User.query.filter_by(user_name = request.form['username'], user_password = request.form['password']).first()
        # print(user.user_name)
        if user:
            return errorResponse('该用户已存在！')
        else:
            newUser = User(user_name = request.form['username'], user_password = request.form['password'])
            # 存入数据库
            db.session.add(newUser)
            db.session.commit()
            return redirect('/user/login')
    else:
        return render_template('register.html')

# 登出页面
@ub.route('/logout')
def logout():
    session.clear()
    return redirect('/user/login')